use super::ToolResult;
use super::WriteFileArgs;
use crate::models::ProjectConfig;
use crate::utils::file_ops;
use anyhow::{Context, Result};

pub fn write_file(args: &WriteFileArgs, context: &ProjectConfig) -> Result<ToolResult> {
    let full_path = file_ops::join_paths(&context.path.to_string_lossy(), &args.file_path)
        .with_context(|| {
            format!(
                "Failed to join paths: {} and {}",
                context.path.to_string_lossy(),
                args.file_path
            )
        })?;

    println!("write_file:{}", full_path.to_string_lossy());

    let _ = file_ops::write_file(&full_path, &args.content, false)
        .context(format!("文件:{}, 写入失败", full_path.to_string_lossy()));

    let message = format!("`{}`成功写入", args.file_path);
    Ok(ToolResult::new(
        args.call_id.clone().unwrap_or_default(),
        args.name.clone().unwrap_or_default(),
        &message,
    ))
}
